package com.example.exception;

import com.example.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * ClassName:ParamExceptionHandler
 * Package:com.example.exception
 * User:HP
 * Date:2025/8/18
 * Time:下午7:58
 * Author 周东汉
 * Version 1.0
 * Description:全局异常处理类，用于拦截并处理系统中的异常
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(value = BindException.class)
    public Result handleBindException(BindException e) {

        // 获取所有参数校验错误信息
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuilder sb = new StringBuilder("参数校验失败：");

        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(' ');
        }

        log.error("参数绑定异常: {}", sb);
        return Result.error(400, sb.toString());
    }

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return Result.error(e.getCode(), e.getMsg());
    }

    // 处理Spring Security的认证异常
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result handleSpringAuthenticationException(
            org.springframework.security.core.AuthenticationException e) {
        return Result.error(401, e.getMessage());
    }

    // 处理Spring Security的权限异常
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result handleSpringAccessDeniedException(
            org.springframework.security.access.AccessDeniedException e) {
        return Result.error(403, "权限不足");
    }

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return Result.error("系统异常!");
    }
}
